import os, shutil, time, pytest, click

from util.server import Server
from util.user_log import log, log_dir
from base import config
from util.operate_config import OperateConfig

op_config = OperateConfig()
report_path = config.file_dir.dir_report
server = Server()

class RunMain:
    @classmethod
    def rm_dir(cls, num=3):
        # 删除报告文件夹
        path_report = report_path
        path_log = log_dir

        def get_file_list(path, func):
            return [file for file in os.listdir(path) if func(os.path.join(path, file))]

        def rm_file(file=None, dir=None):
            path = dir if dir else file
            file_list = get_file_list(path, os.path.isdir) if dir else get_file_list(path, os.path.isfile)
            len_dir = len(file_list)
            if len_dir > num:
                for i in range(len_dir - num):
                    if i == config.file_dir.appium_log.split('\\')[-1]:
                        continue
                    del_path = os.path.join(path, file_list[i])
                    log.debug('保留{}个文件夹，清理旧文件夹：{}'.format(num, del_path))
                    shutil.rmtree(del_path) if dir else os.remove(del_path) if file else None

        rm_file(dir=path_report)
        rm_file(file=path_log)

    @classmethod
    def init_env(cls, now_time):
        # 创建报告中的图片目录
        os.mkdir(report_path + now_time)
        a01 = report_path + now_time + "\\image\\"
        os.mkdir(a01)

    @classmethod
    def pytest_main(cls, m=None, debug=None, xdist=0, html=None):
        now_time = time.strftime("%Y_%m_%d_%H_%M_%S")
        cls.init_env(now_time)
        html_report = os.path.join(report_path, now_time, "report.html")
        xml_report = os.path.join(report_path, now_time, "junit-xml.xml")
        addopts = config.addopts.split(' ')
        rerun = str(config.rerun)
        cmd = None
        if html:
            cmd = addopts + ["--html=" + html_report,
                             "--junit-xml=" + xml_report,
                             "--self-contained-html"]
        if xdist > 1:
            cmd = ['-n', str(xdist)] + addopts
        log.debug('pytest运行命令：{}'.format(cmd))
        pytest.main(cmd)
        cls.rm_dir()


# @click.command()
# @click.option('-m', default=None, help='输入运行模式：run 或 debug.')
def run(debug=False, xdist=0, html=True):
    run_main = RunMain
    server.__call__()
    run_main.pytest_main(debug=debug, xdist=debug, html=html)
    # server.close_server(server.process_appium)


if __name__ == '__main__':
    run(debug=False, xdist=0, html=True)
